#include "log_grid_dialog.h"
#include "ui_manager.h"
#include "../database/sqlite_manager.h"
#include <iostream>

LogGridDialog::LogGridDialog() {
    builder = nullptr;
    window = nullptr;
    popupMenu = nullptr;
    currentPage = 1;
    totalPages = 0;
    totalCount = 0;
    pageSize = 20;  // 默认每页显示20条记录
}

LogGridDialog::~LogGridDialog() {
    if (builder) {
        g_object_unref(builder);
    }
}

bool LogGridDialog::init() {
    // 创建GtkBuilder
    builder = gtk_builder_new();
    
    // 获取UI文件路径
    std::string ui_path = UIManager::get_ui_path();
    // 替换main.glade为log_grid_dialog.glade
    size_t pos = ui_path.find_last_of("/");
    if (pos != std::string::npos) {
        ui_path = ui_path.substr(0, pos) + "/log_grid_dialog.glade";
    } else {
        ui_path = "UI/log_grid_dialog.glade";
    }
    
    // 从文件加载UI
    GError *error = nullptr;
    if (!gtk_builder_add_from_file(builder, ui_path.c_str(), &error)) {
        std::cerr << "无法加载UI文件 " << ui_path << ": " << error->message << std::endl;
        g_error_free(error);
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }
    
    // 获取窗口对象
    window = GTK_WIDGET(gtk_builder_get_object(builder, "logger_window"));
    if (!window) {
        std::cerr << "无法获取logger_window对象" << std::endl;
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }


    // 连接数据库
    SQLiteManager& dbManager = SQLiteManager::getInstance();
    if (!dbManager.connect()) {
        std::cerr << "无法连接到数据库" << std::endl;
        // 即使数据库连接失败，我们也继续初始化UI
    }
    
    
    // 连接信号
    gtk_builder_connect_signals(builder, nullptr);
    
    // 创建右键菜单
    create_popup_menu();
    
    // 连接TreeView的右键菜单事件
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(builder, "log_treeview"));
    if (treeview) {
        g_signal_connect(treeview, "button-press-event", G_CALLBACK(on_treeview_button_press_event), this);
    }
    
    // 连接分页按钮的信号
    GtkWidget *firstButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_first"));
    if (firstButton) {
        g_signal_connect(firstButton, "clicked", G_CALLBACK(on_first_page_clicked), this);
    }
    
    GtkWidget *prevButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_prev"));
    if (prevButton) {
        g_signal_connect(prevButton, "clicked", G_CALLBACK(on_prev_page_clicked), this);
    }
    
    GtkWidget *nextButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_next"));
    if (nextButton) {
        g_signal_connect(nextButton, "clicked", G_CALLBACK(on_next_page_clicked), this);
    }
    
    GtkWidget *lastButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_last"));
    if (lastButton) {
        g_signal_connect(lastButton, "clicked", G_CALLBACK(on_last_page_clicked), this);
    }
    
    // 连接跳转按钮的信号
    GtkWidget *gotoButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_goto_page"));
    if (gotoButton) {
        g_signal_connect(gotoButton, "clicked", G_CALLBACK(on_goto_page_clicked), this);
    }
    
    // 连接每页显示条数下拉框的信号
    GtkWidget *perPageCombo = GTK_WIDGET(gtk_builder_get_object(builder, "combo_per_page"));
    if (perPageCombo) {
        g_signal_connect(perPageCombo, "changed", G_CALLBACK(on_per_page_changed), this);
        // 设置默认选中项为20条/每页
        gtk_combo_box_set_active(GTK_COMBO_BOX(perPageCombo), 1);
    }
    
    return true;
}

void LogGridDialog::show() {
    if (window) {
        gtk_widget_show_all(window);
    }
}

void LogGridDialog::hide() {
    if (window) {
        gtk_widget_hide(window);
    }
}

GtkWidget* LogGridDialog::get_window() {
    return window;
}

void LogGridDialog::populate_log_data() {
    // 使用默认分页参数调用分页版本
    populate_log_data(currentPage, pageSize);
}

void LogGridDialog::populate_log_data(int page, int pageSize) {
    // 创建数据模型
    GtkListStore *store = gtk_list_store_new(12,
                                            G_TYPE_STRING,  // ID
                                            G_TYPE_STRING,  // 日期
                                            G_TYPE_STRING,  // 时间
                                            G_TYPE_STRING,  // 呼号
                                            G_TYPE_STRING,  // 频段
                                            G_TYPE_STRING,  // 频率
                                            G_TYPE_STRING,  // 模式
                                            G_TYPE_STRING,     // RST发送
                                            G_TYPE_STRING,     // RST接收
                                            G_TYPE_STRING,  // 姓名
                                            G_TYPE_STRING,  // QTH
                                            G_TYPE_STRING); // 备注
    
    // 清空原有数据（这里会自动清空，因为每次都是新建一个store）
    
    // 从SQLite数据库加载数据（分页版本）
    SQLiteManager& dbManager = SQLiteManager::getInstance();
    std::vector<QSORecord> records = dbManager.getAllQSOs(page, pageSize, totalCount);
    
    // 计算总页数
    totalPages = (totalCount + pageSize - 1) / pageSize;
    currentPage = page;
    this->pageSize = pageSize;
    
    // 添加数据库中的记录
    for (const QSORecord& record : records) {
        GtkTreeIter iter;
        gtk_list_store_append(store, &iter);
        gtk_list_store_set(store, &iter,
                          0, record.id.c_str(),
                          1, record.date.c_str(),
                          2, record.time.c_str(),
                          3, record.callsign.c_str(),
                          4, record.band.c_str(),
                          5, record.frequency.c_str(),
                          6, record.mode.c_str(),
                          7, record.rst_sent.c_str(),
                          8, record.rst_rcvd.c_str(),
                          9, record.name.c_str(),
                          10, record.qth.c_str(),
                          11, record.memo.c_str(),
                          -1);
    }
    
    // 获取TreeView并设置模型
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(builder, "log_treeview"));
    if (treeview) {
        gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(store));
        g_object_unref(store); // 释放引用，因为gtk_tree_view_set_model会增加引用
    }
    
    // 更新分页信息显示
    updatePaginationInfo();
}

void LogGridDialog::populate_log_data(const std::string& callsignPrefix) {
    // 使用默认分页参数调用分页版本
    populate_log_data(callsignPrefix, currentPage, pageSize);
}

void LogGridDialog::populate_log_data(const std::string& callsignPrefix, int page, int pageSize) {
    // 创建数据模型
    GtkListStore *store = gtk_list_store_new(12,
                                            G_TYPE_STRING,  // ID
                                            G_TYPE_STRING,  // 日期
                                            G_TYPE_STRING,  // 时间
                                            G_TYPE_STRING,  // 呼号
                                            G_TYPE_STRING,  // 频段
                                            G_TYPE_STRING,  // 频率
                                            G_TYPE_STRING,  // 模式
                                            G_TYPE_STRING,     // RST发送
                                            G_TYPE_STRING,     // RST接收
                                            G_TYPE_STRING,  // 姓名
                                            G_TYPE_STRING,  // QTH
                                            G_TYPE_STRING); // 备注
    
    // 清空原有数据（这里会自动清空，因为每次都是新建一个store）
    
    // 从SQLite数据库加载数据（分页版本，带callsign筛选）
    SQLiteManager& dbManager = SQLiteManager::getInstance();
    std::vector<QSORecord> records = dbManager.getQSOsByCallsign(callsignPrefix, page, pageSize, totalCount);
    
    // 计算总页数
    totalPages = (totalCount + pageSize - 1) / pageSize;
    currentPage = page;
    this->pageSize = pageSize;
    
    // 添加数据库中的记录
    for (const QSORecord& record : records) {
        GtkTreeIter iter;
        gtk_list_store_append(store, &iter);
        gtk_list_store_set(store, &iter,
                          0, record.id.c_str(),
                          1, record.date.c_str(),
                          2, record.time.c_str(),
                          3, record.callsign.c_str(),
                          4, record.band.c_str(),
                          5, record.frequency.c_str(),
                          6, record.mode.c_str(),
                          7, record.rst_sent.c_str(),
                          8, record.rst_rcvd.c_str(),
                          9, record.name.c_str(),
                          10, record.qth.c_str(),
                          11, record.memo.c_str(),
                          -1);
    }
    
    // 获取TreeView并设置模型
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(builder, "log_treeview"));
    if (treeview) {
        gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(store));
        g_object_unref(store); // 释放引用，因为gtk_tree_view_set_model会增加引用
    }
    
    // 更新分页信息显示
    updatePaginationInfo();
}

void LogGridDialog::updatePaginationInfo() {
    // 获取分页信息标签
    GtkWidget *paginationLabel = GTK_WIDGET(gtk_builder_get_object(builder, "label_page_info"));
    if (paginationLabel) {
        // 格式化分页信息字符串
        char paginationText[256];
        snprintf(paginationText, sizeof(paginationText), 
                "第 %d 页 / 共 %d 页 (总计 %d 条记录)", 
                currentPage, totalPages, totalCount);
        
        // 设置标签文本
        gtk_label_set_text(GTK_LABEL(paginationLabel), paginationText);
    }
    
    // 更新分页按钮状态
    GtkWidget *prevButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_prev"));
    GtkWidget *nextButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_next"));
    GtkWidget *firstButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_first"));
    GtkWidget *lastButton = GTK_WIDGET(gtk_builder_get_object(builder, "btn_last"));
    
    if (prevButton) {
        // 如果是第一页，则禁用上一页按钮
        gtk_widget_set_sensitive(prevButton, currentPage > 1);
    }
    
    if (nextButton) {
        // 如果是最后一页，则禁用下一页按钮
        gtk_widget_set_sensitive(nextButton, currentPage < totalPages);
    }
    
    if (firstButton) {
        // 如果是第一页，则禁用第一页按钮
        gtk_widget_set_sensitive(firstButton, currentPage > 1);
    }
    
    if (lastButton) {
        // 如果是最后一页，则禁用最后一页按钮
        gtk_widget_set_sensitive(lastButton, currentPage < totalPages);
    }
    
    
}

// 分页按钮回调函数实现
void LogGridDialog::on_first_page_clicked(GtkButton *button, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    logDialog->populate_log_data(1, logDialog->pageSize);
}

void LogGridDialog::on_prev_page_clicked(GtkButton *button, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    if (logDialog->currentPage > 1) {
        logDialog->populate_log_data(logDialog->currentPage - 1, logDialog->pageSize);
    }
}

void LogGridDialog::on_next_page_clicked(GtkButton *button, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    if (logDialog->currentPage < logDialog->totalPages) {
        logDialog->populate_log_data(logDialog->currentPage + 1, logDialog->pageSize);
    }
}

void LogGridDialog::on_last_page_clicked(GtkButton *button, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    logDialog->populate_log_data(logDialog->totalPages, logDialog->pageSize);
}

void LogGridDialog::on_goto_page_clicked(GtkButton *button, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    
    // 获取页码输入框
    GtkWidget *entryPageNumber = GTK_WIDGET(gtk_builder_get_object(logDialog->builder, "entry_page_number"));
    if (entryPageNumber) {
        // 获取输入的页码
        const gchar *text = gtk_entry_get_text(GTK_ENTRY(entryPageNumber));
        if (text && strlen(text) > 0) {
            int page = atoi(text);
            // 验证页码有效性
            if (page > 0 && page <= logDialog->totalPages) {
                logDialog->populate_log_data(page, logDialog->pageSize);
            } else {
                // 页码无效，显示错误提示
                GtkWidget *dialog = gtk_message_dialog_new(
                    GTK_WINDOW(logDialog->window),
                    GTK_DIALOG_MODAL,
                    GTK_MESSAGE_ERROR,
                    GTK_BUTTONS_OK,
                    "请输入有效的页码 (1-%d)", logDialog->totalPages
                );
                gtk_dialog_run(GTK_DIALOG(dialog));
                gtk_widget_destroy(dialog);
            }
        }
    }
}

void LogGridDialog::on_per_page_changed(GtkComboBox *combo, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    
    // 获取选中的每页显示条数
    gchar *text = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(combo));
    if (text) {
        int newPageSize = atoi(text);
        g_free(text);
        
        // 如果每页显示条数发生变化，重新加载第一页数据
        if (newPageSize != logDialog->pageSize) {
            logDialog->pageSize = newPageSize;
            logDialog->populate_log_data(1, logDialog->pageSize);
        }
    }
}

void LogGridDialog::create_popup_menu() {
    std::cout << "开始创建右键菜单" << std::endl;
    
    // 从Glade文件获取菜单对象
    popupMenu = GTK_WIDGET(gtk_builder_get_object(builder, "log_popup_menu"));
    
    if (popupMenu) {
        std::cout << "成功获取到popupMenu对象" << std::endl;
        
        // 连接菜单项的点击事件
        GtkWidget *menuEdit = GTK_WIDGET(gtk_builder_get_object(builder, "menu_edit"));
        if (menuEdit) {
            std::cout << "成功获取到menuEdit对象" << std::endl;
            g_signal_connect(menuEdit, "activate", G_CALLBACK(on_menu_edit_clicked), this);
        } else {
            std::cout << "无法获取menuEdit对象" << std::endl;
        }
        
        GtkWidget *menuQslSent = GTK_WIDGET(gtk_builder_get_object(builder, "menu_qsl_sent"));
        if (menuQslSent) {
            std::cout << "成功获取到menuQslSent对象" << std::endl;
            g_signal_connect(menuQslSent, "activate", G_CALLBACK(on_menu_qsl_sent_clicked), this);
        } else {
            std::cout << "无法获取menuQslSent对象" << std::endl;
        }
        
        GtkWidget *menuQslReceived = GTK_WIDGET(gtk_builder_get_object(builder, "menu_qsl_received"));
        if (menuQslReceived) {
            std::cout << "成功获取到menuQslReceived对象" << std::endl;
            g_signal_connect(menuQslReceived, "activate", G_CALLBACK(on_menu_qsl_received_clicked), this);
        } else {
            std::cout << "无法获取menuQslReceived对象" << std::endl;
        }
        
        GtkWidget *menuDelete = GTK_WIDGET(gtk_builder_get_object(builder, "menu_delete"));
        if (menuDelete) {
            std::cout << "成功获取到menuDelete对象" << std::endl;
            g_signal_connect(menuDelete, "activate", G_CALLBACK(on_menu_delete_clicked), this);
        } else {
            std::cout << "无法获取menuDelete对象" << std::endl;
        }
        
        GtkWidget *menuQslRequested = GTK_WIDGET(gtk_builder_get_object(builder, "menu_qsl_requested"));
        if (menuQslRequested) {
            std::cout << "成功获取到menuQslRequested对象" << std::endl;
            g_signal_connect(menuQslRequested, "activate", G_CALLBACK(on_menu_qsl_requested_clicked), this);
        } else {
            std::cout << "无法获取menuQslRequested对象" << std::endl;
        }
    } else {
        std::cout << "无法获取popupMenu对象，检查Glade文件中是否正确定义了log_popup_menu" << std::endl;
    }
}

// 获取当前选中的记录
bool LogGridDialog::get_selected_record(QSORecord& record) {
    // 获取当前选中的行
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(builder, "log_treeview"));
    if (!treeview) {
        std::cerr << "无法获取log_treeview对象" << std::endl;
        return false;
    }
    
    GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview));
    GtkTreeModel *model;
    GtkTreeIter iter;
    
    if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
        // 获取选中行的数据
        gchar *id_str, *date_str, *time_str, *callsign_str, *band_str, *frequency_str, *mode_str, *rst_sent_str, *rst_rcvd_str, *name_str, *qth_str, *memo_str;
        
        gtk_tree_model_get(model, &iter,
                          0, &id_str,
                          1, &date_str,
                          2, &time_str,
                          3, &callsign_str,
                          4, &band_str,
                          5, &frequency_str,
                          6, &mode_str,
                          7, &rst_sent_str,
                          8, &rst_rcvd_str,
                          9, &name_str,
                          10, &qth_str,
                          11, &memo_str,
                          -1);
        
        // 填充QSORecord对象
        record.id = id_str ? id_str : "";
        record.date = date_str ? date_str : "";
        record.time = time_str ? time_str : "";
        record.callsign = callsign_str ? callsign_str : "";
        record.band = band_str ? band_str : "";
        record.frequency = frequency_str ? frequency_str : "";
        record.mode = mode_str ? mode_str : "";
        record.rst_sent = rst_sent_str ? rst_sent_str : "";
        record.rst_rcvd = rst_rcvd_str ? rst_rcvd_str : "";
        record.name = name_str ? name_str : "";
        record.qth = qth_str ? qth_str : "";
        record.memo = memo_str ? memo_str : "";
        
        // 释放字符串内存
        g_free(id_str);
        g_free(date_str);
        g_free(time_str);
        g_free(callsign_str);
        g_free(band_str);
        g_free(frequency_str);
        g_free(mode_str);
        g_free(rst_sent_str);
        g_free(rst_rcvd_str);
        g_free(name_str);
        g_free(qth_str);
        g_free(memo_str);
        
        return true;
    } else {
        std::cout << "没有选中任何行" << std::endl;
        return false;
    }
}

// "编辑"菜单项点击处理函数
void LogGridDialog::on_menu_edit_clicked(GtkMenuItem *menuitem, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    std::cout << "编辑菜单项被点击" << std::endl;
    
    // 获取当前选中的行
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(logDialog->builder, "log_treeview"));
    if (!treeview) {
        std::cerr << "无法获取log_treeview对象" << std::endl;
        return;
    }
    
    GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview));
    GtkTreeModel *model;
    GtkTreeIter iter;
    
    if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
        // 获取选中行的数据
        gchar *id_str, *date_str, *time_str, *callsign_str, *band_str, *frequency_str, *mode_str, *rst_sent_str, *rst_rcvd_str, *name_str, *qth_str, *memo_str;
        
        gtk_tree_model_get(model, &iter,
                          0, &id_str,
                          1, &date_str,
                          2, &time_str,
                          3, &callsign_str,
                          4, &band_str,
                          5, &frequency_str,
                          6, &mode_str,
                          7, &rst_sent_str,
                          8, &rst_rcvd_str,
                          9, &name_str,
                          10, &qth_str,
                          11, &memo_str,
                          -1);
        
        // 创建QSORecord对象
        QSORecord record;
        record.id = id_str ? id_str : "";
        record.date = date_str ? date_str : "";
        record.time = time_str ? time_str : "";
        record.callsign = callsign_str ? callsign_str : "";
        record.band = band_str ? band_str : "";
        record.frequency = frequency_str ? frequency_str : "";
        record.mode = mode_str ? mode_str : "";
        record.rst_sent = rst_sent_str ? rst_sent_str : "";
        record.rst_rcvd = rst_rcvd_str ? rst_rcvd_str : "";
        record.name = name_str ? name_str : "";
        record.qth = qth_str ? qth_str : "";
        record.memo = memo_str ? memo_str : "";
        
        // 创建并显示编辑对话框
        QSOEditDialog *editDialog = new QSOEditDialog();
        if (editDialog->init(record)) {
            editDialog->show();
        } else {
            std::cerr << "无法初始化编辑对话框" << std::endl;
            delete editDialog;
        }
        
        // 释放字符串内存
        g_free(id_str);
        g_free(date_str);
        g_free(time_str);
        g_free(callsign_str);
        g_free(band_str);
        g_free(frequency_str);
        g_free(mode_str);
        g_free(rst_sent_str);
        g_free(rst_rcvd_str);
        g_free(name_str);
        g_free(qth_str);
        g_free(memo_str);
    } else {
        std::cout << "没有选中任何行" << std::endl;
    }
}

bool LogGridDialog::setDataFieldValue(GtkMenuItem *menuitem, gpointer data, const std::string& field, const std::string& value) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    // TODO: 实现标记已发QSL功能
    //取得grid中的当前选中的行
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(logDialog->builder, "log_treeview"));
    if (!treeview) {
        std::cerr << "无法获取log_treeview对象" << std::endl;
        return false;
    }
    
    GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview));
    GtkTreeModel *model;
    GtkTreeIter iter;
    
    if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
        // TODO: 实现标记已发QSL功能
        //取得ID
        gchar *id_str;
        gtk_tree_model_get(model, &iter, 0, &id_str, -1);
        std::cout << "ID: " << id_str << std::endl;

        SQLiteManager& dbManager = SQLiteManager::getInstance();
        if (dbManager.setDataFieldValue(id_str, field, value)) {
            std::cerr << "标记" << field << "成功，ID: " << id_str << std::endl;
            // 标记成功后刷新TreeView
            // logDialog->populate_log_data(logDialog->currentPage, logDialog->pageSize);
            return true;
        } else {
            std::cerr << "标记" << field << "失败，ID: " << id_str << std::endl;
            // 显示错误提示
            GtkWidget *errorDialog = gtk_message_dialog_new(
                GTK_WINDOW(logDialog->window),
                GTK_DIALOG_MODAL,
                GTK_MESSAGE_ERROR,
                GTK_BUTTONS_OK,
                "%s",
                ("标记" + field + "失败！").c_str()
            );
            gtk_dialog_run(GTK_DIALOG(errorDialog));
            gtk_widget_destroy(errorDialog);
            return false;
        }
        g_free(id_str);
    } else {
        std::cout << "没有选中任何行" << std::endl;
        return false;
    }
}

// "标记已发QSL"菜单项点击处理函数
void LogGridDialog::on_menu_qsl_sent_clicked(GtkMenuItem *menuitem, gpointer data) {
    // TODO: 实现标记已发QSL功能
    std::cout << "标记已发QSL菜单项被点击" << std::endl;
    if (!setDataFieldValue(menuitem, data, "sended_QSL", "1")) {
        return;
    }
}

// "标记已收QSL"菜单项点击处理函数
void LogGridDialog::on_menu_qsl_received_clicked(GtkMenuItem *menuitem, gpointer data) {
    // TODO: 实现标记已收QSL功能
    std::cout << "标记已收QSL菜单项被点击" << std::endl;    
    if (!setDataFieldValue(menuitem, data, "rcved_QSL", "1")) {
        return;
    }
}

// "标记需发QSL"菜单项点击处理函数
void LogGridDialog::on_menu_qsl_requested_clicked(GtkMenuItem *menuitem, gpointer data) {
    // TODO: 实现标记需发QSL功能
    std::cout << "标记需发QSL菜单项被点击" << std::endl;
    if (!setDataFieldValue(menuitem, data, "requested_QSL", "1")) {
        return;
    }
}

// TreeView右键点击事件处理函数
gboolean LogGridDialog::on_treeview_button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    
    // 检查是否是右键点击
    if (event->type == GDK_BUTTON_PRESS && event->button == 3) {
        std::cout << "检测到右键点击事件" << std::endl;
        // 显示右键菜单
        if (logDialog->popupMenu) {
            std::cout << "尝试显示右键菜单" << std::endl;
            gtk_menu_popup_at_pointer(GTK_MENU(logDialog->popupMenu), (GdkEvent*)event);
            return TRUE; // 停止事件传播
        } else {
            std::cout << "popupMenu为空" << std::endl;
        }
    }
    
    return FALSE; // 继续事件传播
}

// "删除"菜单项点击处理函数
void LogGridDialog::on_menu_delete_clicked(GtkMenuItem *menuitem, gpointer data) {
    LogGridDialog *logDialog = static_cast<LogGridDialog*>(data);
    std::cout << "删除菜单项被点击" << std::endl;
    
    // 获取当前选中的行
    GtkWidget *treeview = GTK_WIDGET(gtk_builder_get_object(logDialog->builder, "log_treeview"));
    if (!treeview) {
        std::cerr << "无法获取log_treeview对象" << std::endl;
        return;
    }
    
    GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview));
    GtkTreeModel *model;
    GtkTreeIter iter;
    
    if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
        // 获取选中行的ID
        gchar *id_str;
        gtk_tree_model_get(model, &iter, 0, &id_str, -1);
        
        if (id_str) {
            // 显示确认对话框
            GtkWidget *dialog = gtk_message_dialog_new(
                GTK_WINDOW(logDialog->window),
                GTK_DIALOG_MODAL,
                GTK_MESSAGE_QUESTION,
                GTK_BUTTONS_YES_NO,
                "确定要删除这条记录吗？\n\nID: %s", id_str
            );
            
            gint result = gtk_dialog_run(GTK_DIALOG(dialog));
            gtk_widget_destroy(dialog);
            
            if (result == GTK_RESPONSE_YES) {
                // 用户确认删除，调用数据库删除函数
                SQLiteManager& dbManager = SQLiteManager::getInstance();
                if (dbManager.deleteQSO(id_str)) {
                    std::cout << "成功删除记录，ID: " << id_str << std::endl;
                    // 删除成功后刷新TreeView
                    logDialog->populate_log_data(logDialog->currentPage, logDialog->pageSize);
                } else {
                    std::cerr << "删除记录失败，ID: " << id_str << std::endl;
                    // 显示错误提示
                    GtkWidget *errorDialog = gtk_message_dialog_new(
                        GTK_WINDOW(logDialog->window),
                        GTK_DIALOG_MODAL,
                        GTK_MESSAGE_ERROR,
                        GTK_BUTTONS_OK,
                        "删除记录失败！"
                    );
                    gtk_dialog_run(GTK_DIALOG(errorDialog));
                    gtk_widget_destroy(errorDialog);
                }
            }
            
            // 释放字符串内存
            g_free(id_str);
        }
    } else {
        std::cout << "没有选中任何行" << std::endl;
        // 提示用户需要先选择一行
        GtkWidget *infoDialog = gtk_message_dialog_new(
            GTK_WINDOW(logDialog->window),
            GTK_DIALOG_MODAL,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "请先选择要删除的记录！"
        );
        gtk_dialog_run(GTK_DIALOG(infoDialog));
        gtk_widget_destroy(infoDialog);
    }
}